#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: utils.py
@contact: zwb15083976291@163.com
@time: 2022/02/28
"""
import json

from django.conf import settings

from common.models import BlogArticle
from common.serializers.serializer import SearchArticlesSerializer
from utils.redis_clients import RedisClient


def add_article_search_cached_data():
    with RedisClient().pipeline() as redis_pipeline:
        # 将数据过期掉
        redis_pipeline.expire(getattr(settings, "SEARCH_ARTICLES_KEY"), 0)
        data = SearchArticlesSerializer(serial_fields=['id', 'articles_title', 'article_describe'],
                                        instance=BlogArticle.objects.filter(articles_status=0).all(), many=True).data
        for item in data:
            redis_pipeline.hset(getattr(settings, "SEARCH_ARTICLES_KEY"),
                                item['articles_title'].lower() + item['article_describe'].lower(),
                                json.dumps(item, ensure_ascii=False))
        # 设置数据的过期时间
        redis_pipeline.expire(getattr(settings, "SEARCH_ARTICLES_KEY"), getattr(settings, "SEARCH_ARTICLES_KEY_EXPIRE"))
        redis_pipeline.execute()
    return True
